package com.youbug.mall.search.feign.impl;

import com.youbug.common.to.es.SkuEsModel;
import com.youbug.mall.product_pms.feign.ISearchFeignService;
import com.youbug.mall.search.constant.EsConstant;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SearchFeignServiceImpl implements ISearchFeignService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void productStatusUp(List<SkuEsModel> models) {
        Iterable<SkuEsModel> skuEsModels = elasticsearchRestTemplate.save(models, IndexCoordinates.of(EsConstant.PRODUCT_INDEX));
    }

    @Override
    public void productStatusDown(Long spuId) {
        NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder();

        MatchQueryBuilder spuIdQuery = QueryBuilders.matchQuery("spuId", spuId);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        boolQueryBuilder.must(spuIdQuery);

        searchQueryBuilder.withQuery(boolQueryBuilder);

        NativeSearchQuery query = searchQueryBuilder.build();

        elasticsearchRestTemplate.delete(query, SkuEsModel.class, IndexCoordinates.of(EsConstant.PRODUCT_INDEX));

    }
}
